package cheme.ProcessEditor;

import org.eclipse.gef.EditDomain;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.gef.GraphicalViewer;
import org.eclipse.gef.commands.Command;
import org.eclipse.swt.events.KeyEvent;

public abstract class AbstractKeyProcess implements IProcessKey
{
	private GraphicalEditPart focusPart = null;
	
	protected void setViewer()
	{
	}
	
	protected static GraphicalViewer getViewer(GraphicalEditPart part)
	{
		return (GraphicalViewer)getRoot(part).getViewer();
	}

	public void setFocusPart(GraphicalEditPart focusPart)
	{
		this.focusPart = focusPart;
	}

	public GraphicalEditPart getFocusPart()
	{
		return focusPart;
	}
	
	protected static EditPart getRoot(EditPart part)
	{
		EditPart root = part;
		while(null != root.getParent())
		{
			root = root.getParent();
		}
		
		return root;
	}

	public boolean handleKey(KeyEvent event, GraphicalEditPart focusPart)
	{
		setFocusPart(focusPart);
		
		return true;
	}
	
	/**
	* Executes the given command on the command stack.
	* @param command the command to execute
	*/
	protected void executeCommand(Command command)
	{
		try
		{
			getEditDomain().getCommandStack().execute(command);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	private EditDomain getEditDomain()
	{
		if(null != getFocusPart())
		{
			return getFocusPart().getViewer().getEditDomain();
		}
		
		return null;
	}
}
